<template>
  <el-dialog
    class="public-dialog"
    title="导入"
    width="720"
    v-model="importVisible"
    @close="handleClose"
    draggable
    align-center
    destroy-on-close
  >
    <div>
      <fileContent
        :type="formValue.type"
        :count="formValue.count"
        :accept="formValue.accept"
        ref="fileContentRef"
      />
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import fileContent from "./fileContent.vue";
import { submit } from "./config.js";
const formValue = reactive({
  count: 1,
  type: null,
  urlType: null,
  accept: null,
});
const importVisible = ref(false);
const emit = defineEmits(["refresh", "close"]);
const loading = ref(false);
const fileContentRef = ref();
const disabled = ref(false);
const business_params = ref({})
const open = (data) => {
  formValue.count = data?.count || 1;
  formValue.type = data?.type || null;
  formValue.urlType = data?.urlType || null;
  formValue.accept =
    data?.accept ||
    ".csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  importVisible.value = true;
  business_params.value = data?.business_params||null
};

const handleSave = async () => {
  let file = fileContentRef.value.getFileList();
  if (file?.length === 0) {
    ElMessage.warning("请上传文件");
    return;
  }
  if (!formValue?.urlType) {
    return;
  }
  loading.value = true;
  try {
    const { code, message } = await submit(formValue.urlType, {
      business_file: file[0].response,
      business_params:business_params.value
    });
    console.log(code, message);
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("导入成功!");
    handleClose(true);
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  fileContentRef.value.clearFiles();
  formValue.count = 1;
  formValue.type = null;
  formValue.urlType = null;
  importVisible.value = false;
  emit("close");
  if (refresh) emit("refresh");
};
defineExpose({
  open,
});
</script>
